package org.lzfto.flink.demo.business.flinkTest.flinkObjects.function.map;

import org.apache.flink.api.common.functions.MapFunction;
import org.lzfto.flink.demo.business.orders.OrderCommon;
import org.lzfto.flink.demo.business.orders.SimpleOrder;
import org.lzfto.flink.demo.business.orders.SimpleOrderAgg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson2.JSON;

/**
*把普通的订单转为加盐的汇总订单
*@author lzfto
*@创建时间 2025年6月24日 11:47:41
*/
public class StrToSaltOrderMapFun<T> implements MapFunction<String, T> {
	private static final long serialVersionUID = 1L;
	
	private final  Logger LOGGER = LoggerFactory.getLogger(getClass());

	private String grpType;
	private Class<T> t;
	
	public  StrToSaltOrderMapFun(String grpType,Class<T> t) {
		this.grpType=grpType;
		this.t=t;
		LOGGER.info("创建订单转换器，分组类型:{}",grpType);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public T map(String value) throws Exception {
		if (t.equals(SimpleOrder.class)) {
			SimpleOrder order = JSON.to(SimpleOrder.class, value);
			int randomSalt = (int) (Math.random() * 6); // 生成0~5的随机整数
			String salt = String.valueOf(randomSalt);
			if (grpType.equals(OrderCommon.GRP_TYPE_SEX)) {
				order.setSex(order.getSex() + "-" + salt);
			} else if (grpType.equals(OrderCommon.GRP_TYPE_ZONE)) {
				order.setZoneName(order.getZoneName() + "-" + salt);
			} else {
				order.setSex(order.getSex() + "-" + salt);
			}
			//LOGGER.info("加盐后结果:{}",JSON.toJSONString(agg));
			return (T)order;
		}
		else {
			SimpleOrder order = JSON.to(SimpleOrder.class, value);
			int randomSalt = (int) (Math.random() * 6); // 生成0~5的随机整数
			String salt = String.valueOf(randomSalt);
			SimpleOrderAgg agg = new SimpleOrderAgg();
			if (grpType.equals(OrderCommon.GRP_TYPE_SEX)) {
				agg.setSex(order.getSex() + "-" + salt);
				agg.setZoneName(order.getZoneName());
			} else if (grpType.equals(OrderCommon.GRP_TYPE_ZONE)) {
				agg.setZoneName(order.getZoneName() + "-" + salt);
				agg.setSex(order.getSex());
			} else {
				agg.setSex(order.getSex() + "-" + salt);
				agg.setZoneName(order.getZoneName());
			}
			
			agg.setCount(1);
			agg.setTotal(order.getPrice());
			//LOGGER.info("加盐后结果:{}",JSON.toJSONString(agg));
			return (T)agg;
		}
		
	}

}
